<?php

require_once(APP_DEFAULT_PST . "select.php");

if (!class_exists("PST_AUTOCOMPLETE")) {

    class PST_AUTOCOMPLETE extends PST_SELECT {

        protected $model = null;
        protected $plugin = null;
        protected $model_obj = null;
        protected $conditions = array();
        protected $order = array();
        protected $array = array('type' => 'text', 'class' => 'autocomplete');

        public function __construct($settings) {
            parent::__construct($settings);
            if (isset($this->classparams['model'])) {
                $this->model = $this->classparams['model'];
            }
            $this->js_initial = "autocomplete_init";
            $this->js_params['controller'] = strtolower($this->model) . "s";
            if (isset($this->getObj()->plugin)) {
                $this->js_params['plugin'] = strtolower($this->getObj()->plugin);
            }
        }

        public function renderMaintForm() {
            $this->array['div']['id'] = 'box' . $this->id;
            $this->array['before'] = '<input type="hidden" name="' . $this->name . '" id="' . $this->id . '" />';
            $this->array['after'] = '<img src="' . WWW . 'img/autocomplete.gif">';
            $this->array['name'] = $this->id . '_ac';
            $this->array['id'] = $this->id . '_ac';
            return parent::renderMaintForm();
        }

        public function jsIncludes() {
            return array("presentation/autocomplete.js");
        }

        public function ajax_obtener_valores($val) {
            global $MODEL;
            $array = array();

            $data = $MODEL->query("SELECT " . $MODEL->primaryKey . ", " . $MODEL->displayField . " 
                                   FROM " . $MODEL->useTable . " 
                                   WHERE " . $MODEL->displayField . " LIKE '%" . $val . "%'");
            foreach ($data as $d) {
                $array[] = array(
                    "id" => $d[$MODEL->useTable][$MODEL->primaryKey],
                    "label" => $d[$MODEL->useTable][$MODEL->displayField],
                    "value" => $d[$MODEL->useTable][$MODEL->displayField]
                );
            }

            return json_encode($array);
        }

    }

}